import _objectSpread from "@babel/runtime/helpers/esm/objectSpread2";
import _slicedToArray from "@babel/runtime/helpers/esm/slicedToArray";
import _isEqual from "lodash/isEqual";

/**
 *
 * 自动设置Table高度
 * @data: 2020/8/19
 */
import React, { useRef, useEffect, useState } from 'react';
import ReactDOM from 'react-dom';

// export interface AutoRestHeightProps extends HTMLAttributes<Element> {
//   diff: number;  // 差距间隙，可以用作微调
//   topSelector: string; // 内部 top 位置的 query selector
// }

/**
 * 自动适应高度
 */
var AutoRestHeight = function AutoRestHeight(_ref) {
  var children = _ref.children,
      _ref$diff = _ref.diff,
      diff = _ref$diff === void 0 ? 80 : _ref$diff,
      topSelector = _ref.topSelector,
      style = _ref.style,
      bodyStyle = _ref.bodyStyle,
      _ref$type = _ref.type,
      type = _ref$type === void 0 ? 'c7n' : _ref$type;
  var childrenRef = useRef(null);
  var frame = useRef(0);

  var _useState = useState('auto'),
      _useState2 = _slicedToArray(_useState, 2),
      height = _useState2[0],
      setHeight = _useState2[1];

  useEffect(function () {
    var resize = function resize() {
      if (childrenRef.current) {
        // eslint-disable-next-line
        var childrenRefWrapperDom = ReactDOM.findDOMNode(childrenRef.current);
        var childrenRefDom = childrenRefWrapperDom;

        if (topSelector) {
          childrenRefDom = childrenRefDom.querySelector(topSelector);
        }

        var _childrenRefDom$getBo = childrenRefDom.getBoundingClientRect(),
            offsetTop = _childrenRefDom$getBo.top;

        setHeight(window.innerHeight - offsetTop - diff);

        if (childrenRef.current.handleResize) {
          childrenRef.current.handleResize();
        }
      }
    };

    resize();

    var handler = function handler() {
      cancelAnimationFrame(frame.current);
      frame.current = requestAnimationFrame(resize);
    };

    window.addEventListener('resize', handler);
    return function () {
      cancelAnimationFrame(frame.current);
      window.removeEventListener('resize', handler);
    };
  }, []);

  if (React.isValidElement(children)) {
    if (_isEqual(type, 'antd')) {
      var newScroll = {
        y: height - 40
      };

      if (children.props && children.props.scroll) {
        var newX = children.props.scroll.x;
        newScroll = {
          x: newX,
          y: newScroll.y
        };
      }

      return React.cloneElement(children, {
        ref: childrenRef,
        scroll: newScroll,
        bodyStyle: _objectSpread(_objectSpread({}, bodyStyle), {}, {
          height: height - 40
        }),
        style: _objectSpread(_objectSpread({}, style), {}, {
          height: height
        })
      });
    } else {
      return React.cloneElement(children, {
        ref: childrenRef,
        style: _objectSpread(_objectSpread({}, style), {}, {
          height: height
        })
      });
    }
  } else {
    return null;
  }
};

export default AutoRestHeight;